<template>
  <div class="page_root" data-page-name="auth" data-page-identification="r_8y61ive110">
    <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
      <!-- begin vid_83qciysr9i 自定义模板_7u4afzgigy -->

      <!-- end vid_83qciysr9i 自定义模板_7u4afzgigy -->
    </a-spin>
  </div>
</template>
<script setup>
import {
  h, ref, reactive, toRaw, markRaw, watch, computed,
  onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, onActivated, onDeactivated
} from "vue";
import { useRoute, useRouter } from 'vue-router';
const router = useRouter();
const route = useRoute();
import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
import { cloneDeep, localGet, merge, getDifferenceArray, traversalTreeStructure, checkCaseCondition, renderStringInTemplate, handleBreadcrumbJump, throttle, permission } from '@/utils/index';
import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is';
import dayjs from 'dayjs';
import { getPagePcChartsDataSourceConvert } from '@/utils/chart';
import { message, notification, Modal } from 'ant-design-vue'
import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate } from '@/utils/format';
/*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 *** PUBLISH_EXEGESIS ***/



  // 获取传入的流程ID
const props = defineProps({
    processInstanceId: {
      type: String
    }
  })
const immediateWatch = (source, callback) => {
  watch(source, callback, {deep: true,immediate: true })
}



/* -------------------------- 属性定义 -------------------------- */

const setTimeOutList = [];
const pageLoading = reactive({
  loading: false,
  tip: undefined
});
const authInfo = localGet('app-user-store');




// 处理校验
const setSubFormName =(parentInfo, name)=>{
  return [parentInfo.parents, parentInfo.cycleIndex, name];
}


/* ========================== 属性定义 ========================== */


/* -------------------------- 元素数据引用 -------------------------- */


/* ========================== 元素数据引用 ========================== */


/* -------------------------- 页面数据 -------------------------- */

/* ========================== 页面数据 ========================== */


/* -------------------------- 响应 -------------------------- */

/* ========================== 响应 ========================== */


/* -------------------------- 函数 -------------------------- */

/* ========================== 函数 ========================== */


/* -------------------------- 页面参数 -------------------------- */

const pageParameter_state = reactive({
  'processInstanceId': props.processInstanceId ?? route.query.processInstanceId,
})

/* ========================== 页面参数 ========================== */


/* -------------------------- 组件事件处理方法 -------------------------- */

// ---------------------------- 组件数据同步 ----------------------------

// ============================ 组件数据同步 ============================


/* ========================== 组件事件处理方法 ========================== */


/* -------------------------- 生命周期 -------------------------- */
onMounted(() => { ;

});

onUnmounted(() => {
  // 销毁定时器
  setTimeOutList.forEach(({ repeat, timer }) => {
    repeat ?  clearInterval(timer): clearTimeout(timer);
  });
});

/* ========================== 生命周期 ========================== */


/* -------------------------- 数据关联处理 -------------------------- */





/* -------------------------- 表单数据同步 -------------------------- */
/* ========================== 表单数据同步 ========================== */

/* ========================== 数据关联处理 ========================== */


/* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

/* ========================== 不同组件自定义的处理逻辑 ========================== */


// ================================定制化逻辑========================================
const stateForm = reactive({
  tenantId: null,
  sessionKey: null,
  userId: null,
  mobile: null,
  productId: null,
  // 准备跳转的页面
  getTidUrl: null,
  // 需要截取前缀进行获取tenantId的地址
  newUrl: null
});
var currentURL = window.location.href;
// 截取登陆所需参数
function getParameterByName(name, url = window.location.href) {
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

stateForm.sessionKey = getParameterByName('sessionKey', currentURL);
stateForm.userId = getParameterByName('userId', currentURL);
stateForm.mobile = getParameterByName('mobile', currentURL);

getNewUrl()
// 获取跳转地址和获取tenanId地址
async function getNewUrl() {
  try {
    const response = await post('/solution-ppm/api/v2/built-in-system-ppm/wechat_auth_config/query/user_address', {
      userId: stateForm.userId
    });
    const result = response.data; // 获取响应数据
    console.log(result, '跳转地址');
    if (result.productUri) {
      stateForm.getTidUrl = result.appUri;
      stateForm.newUrl = result.productUri;
      getTenantId();
    }
  } catch (error) {
    // 请求失败时调用 getToken
    getToken();

    // 这里处理请求错误
    console.log('getNewUrl出现错误:', error);
  }
}
// 获取tenanId
async function getTenantId() {
  try {
    let firstSlashIndex = stateForm.newUrl.indexOf('/', 8);
    let prefix;

    if (firstSlashIndex !== -1) {
      prefix = stateForm.newUrl.substring(0, firstSlashIndex);
      let protocols = ['http://', 'https://'];
      let protocol = protocols.find(p => prefix.includes(p));

      if (protocol) {
        let result = prefix.substring(protocol.length);
        // result = result + '/app_50000005/';
        console.log(result, 'result');
        let data = await post(`/base/api/v1/product/url`, {
          url: result
        });
        if (data.status === 'success') {
          stateForm.tenantId = data.data.tenantId;
          stateForm.productId = data.data.id;
          console.log(stateForm.tenantId, 'stateForm.tenantId');
          getUser();
        } else {
          console.error('获取tenantId失败');
        }
      } else {
        console.error('未找到 `http://` 或 `https://`');
      }
    } else {
      console.error('无法提取前缀');
    }
  } catch (error) {
    console.error('getTenant1Id出现错误:', error);
  }
}
function getUser() {
  try {
    // let localStorageData = localStorage.getItem('app-user-store');
    let localStorageDataDP = localStorage.getItem('app-user-store');
    // debugger
    if (localStorageDataDP !== null) {
      localStorageDataDP = JSON.parse(localStorageDataDP);
      if (localStorageDataDP.token !== null) {
        console.log('有token调接口校验token的可行性');
        checkToken(localStorageDataDP.token, localStorageDataDP.uuid);
      } else {
        console.log('这里是没有token走的调登录');
        getToken();
      }
    } else {
      getToken();
    }
  } catch (error) {
    console.error('getUser出现错误:', error);
  }
}
// 有token校验token合法性
async function checkToken(token, uuid) {
  try {
    let params = {
      uuid: uuid,
      token: token,
      appId: 'product-c'
    };
    let result = await post('/base/api/v1/valid', params);
    if (result.data === null) {
      // 如果data为null，则执行getToken操作
      getToken();
    } else {
      // 如果data不为null，则执行getNe1wUrl操作
      let newUserData = {
        uuid: uuid,
        token: token,
        productId: stateForm.productId,
        tenantId: stateForm.tenantId,
        appid: 'product-container'
      };
      localStorage.setItem('app-user-store', JSON.stringify(newUserData));
      console.log(localStorage.getItem('app-user-store'));
      window.location.href = stateForm.getTidUrl
    }

  } catch (error) {
    getToken();
    console.error('checkToken出现错误:', error);
  }
}
// 没token获取token
async function getToken() {
  try {
    let uuid = '';
    let token = '';
    const params = {
      sessionKey: stateForm.sessionKey,
      mobile: stateForm.mobile,
      appId: 'product-container',
      withTenantIdFlag: false,
      mobileIsUserName: false,
      tenantId: stateForm.tenantId
    };
    let result = await post('/base/api/v1/open/login', params);
    console.log(result.status, 'getTokenstatus');
    if (result.data) {
      console.log(result, '登陆接口返回');
      uuid = result.data.uuid;
      token = result.data.token;
      let newUserData = {
        uuid: uuid,
        token: token,
        productId: stateForm.productId,
        tenantId: stateForm.tenantId,
        appid: 'product-container'
      };
      localStorage.setItem('app-user-store', JSON.stringify(newUserData));
      localStorage.setItem('app-user', JSON.stringify(newUserData));
      console.log('执行');
      console.log(localStorage.getItem('app-user-store'));
      window.location.href = stateForm.getTidUrl;
    } else {
      message.error('非法账号')
    }
  } catch (error) {
    console.error('getToken出现错误:', error);
   message.error('非法账号')
  }
}
</script>
<style lang="less" scoped>
.page_root {
  width: 100%;
  height: 100%;
  overflow: auto;
}
.page_root :deep(.@{ant-prefix}-spin-nested-loading),
.page_root :deep(.@{ant-prefix}-spin-container)
{
  height: 100%;
}
.page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper)
{
  display: flex;
  flex-flow: column nowrap;
  justify-content: flex-start;
}
.page_root :deep(.@{ant-prefix}-table)
{
  flex: auto;
  overflow: auto;
}
.table-moreBtn_down {
  overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 100px;
}

.table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
  background: #ebf1ff;
}

/*  表格树结构样式处理，展开按钮层级增加*/
:deep(.@{ant-prefix}-table-row-expand-icon) {
  z-index: 1;
}
/*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
:deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
  left: 15px !important;
  width: calc(100% - 15px);
}
:deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
  left: 30px !important;
  width: calc(100% - 30px);
}
:deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
  left: 45px !important;
  width: calc(100% - 45px);
}
:deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
  left: 60px !important;
  width: calc(100% - 60px);
}

/* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
:deep(.@{ant-prefix}-transfer-list)
{
  height: 100%;
  width: 50%;
}
</style>
